package com.koron.css2.newProjectCenter.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.koron.css2.ImportExcelInterface;
import com.koron.css2.baseConfig.bean.BankBean;
import com.koron.css2.baseConfig.bean.WaterTypeBean;
import com.koron.css2.baseConfig.mapper.BankMapper;
import com.koron.css2.baseConfig.mapper.WaterTypeMapper;
import com.koron.css2.common.dto.HeaderInfoDto;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.query.PjMeterQuery;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.newProjectCenter.vo.PjMeterContractExportVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class PjMeterContractImport implements ImportExcelInterface {

    private static Logger logger = LoggerFactory.getLogger(PjMeterContractImport.class);
    @Override
    public MessageBean<?> importExel(SessionFactory factory, UserInfoBean userInfo, RequestBean req, List<Map<String, String>> data, MultipartFile file) {
        try {
            PjMeterQuery pjMeterQuery = JsonUtils.objectToPojo(req.getData(), PjMeterQuery.class);
            PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
            PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);
            WaterTypeMapper waterTypeMapper = factory.getMapper(WaterTypeMapper.class);
            BankMapper bankMapper = factory.getMapper(BankMapper.class);

            Objects.requireNonNull(pjMeterQuery, "参数不能为空");
            PjInfoBean infoBean = pjInfoMapper.selectById(pjMeterQuery.getConsultId());
            Objects.requireNonNull(infoBean, "报装单据不存在");

            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(data);
            List<PjMeterContractExportVO> list = jsonArray.toJavaList(PjMeterContractExportVO.class);
            Map<String, String> cerTypeMap = Tools.mapDicByCode(factory, "IDT");//证件类型
            List<PjMeter> pjMeterList = pjMeterMapper.getList(pjMeterQuery);
            List<PjMeter> resulList = new ArrayList<>();
            if (pjMeterList != null && pjMeterList.size() > 0) {
                PjMeterList.covertMeterInfo(factory, pjMeterList);
            }
            if (ObjectUtil.isNotNull(list) && list.size() > 0 && pjMeterList != null) {
                List<String> userNos = pjMeterList.stream().map(x -> {
                    if (ObjectUtil.isNotNull(x.getUserInfo())) {
                        return x.getUserInfo().getUserNo();
                    }
                    return null;
                }).filter(y -> StringUtils.isNotBlank(y)).collect(Collectors.toList());
                Map<String, List<PjMeter>> groupMap = pjMeterList.stream().collect(Collectors.groupingBy(x -> {
                    return x.getUserInfo().getUserNo();
                }));
                Map<String,String> useWaterTypeMap= MapUtil.reverse(cerTypeMap);
                for (int i = 0; i < list.size(); i++) {
                    PjMeterContractExportVO vo = list.get(i);
                    String userNo = vo.getUserNo();
                    if (!userNos.contains(userNo)) {
                        throw new RuntimeException("用户编号：" + userNo + " 不存在");
                    }
                    List<PjMeter> meterList = groupMap.get(userNo);
                    if (meterList != null) {
                        PjMeter pjMeter = meterList.get(0);
                        pjMeter.getUserInfo().setCtmName(vo.getCtmName());
                        if (StringUtils.isNotBlank(vo.getCertTypeName())&&!cerTypeMap.containsValue(vo.getCertTypeName())) {
                            throw new RuntimeException("证件类型：" + vo.getCertTypeName() + "不存在");
                        }else {
                            pjMeter.getUserInfo().setCertTypeName(vo.getCertTypeName());
                            pjMeter.getUserInfo().setCertType(useWaterTypeMap.get(vo.getCertTypeName()));

                        }
                        // 开户银行名称
                        if (StringUtils.isNotEmpty(vo.getOpenAccountBankName())){
                            BankBean bank = bankMapper.findBankByName(vo.getOpenAccountBankName());
                            if (bank == null){
                                throw new RuntimeException("开户银行" + vo.getOpenAccountBankName() + "不存在");
                            }
                            pjMeter.getAccountInfo().setOpenAccountBank(bank.getId());
                        }
                        if (StringUtils.isNotEmpty(vo.getBankAccount()) && vo.getBankAccount().length() > 19){
                            throw new RuntimeException("银行账号长度超过19位");
                        }
                        // 银行账号检验,如果银行账号存在非法字符，则直接过滤掉其中的非法字符
                        if (StringUtils.isNotEmpty(vo.getBankAccount())){
                            vo.setBankAccount(StringUtils.trim(vo.getBankAccount()));
                            String bankAccount = vo.getBankAccount().chars()
                                    .filter(Character::isDigit)
                                    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                                    .toString();
                            vo.setBankAccount(bankAccount);
                        }
                        // 开户银行名称
                        pjMeter.getAccountInfo().setOpenAccountBankName(vo.getOpenAccountBankName());
                        // 银行账号
                        pjMeter.getAccountInfo().setBankAccount(vo.getBankAccount());
                        // 开户名
                        pjMeter.getAccountInfo().setOpenAccountName(vo.getOpenAccountName());
                        // 证件号
                        pjMeter.getUserInfo().setCertNo(vo.getCertNo());
                        // 客户地址
                        pjMeter.getUserInfo().setCtmAddr(vo.getCtmAddr());
                        // 手机号
                        pjMeter.getUserInfo().setMobile(vo.getMobile());
                        // 停水通知联系人
                        pjMeter.getUserInfo().setStopWaterLinkMobile(vo.getStopWaterLinkMobile());
                        // 用水类型
                        pjMeter.getUserInfo().setUseWaterTypeName(vo.getUseWaterTypeName());
                        // 水表安装地址
                        pjMeter.getUserInfo().setSetupMeterAddr(vo.getSetupMeterAddr());
                        // 用水类型
                        if (StringUtils.isNotBlank(vo.getUseWaterTypeName())) {
                            WaterTypeBean waterTypeByName = waterTypeMapper.findWaterTypeByName(vo.getUseWaterTypeName());
                            if (ObjectUtil.isNull(waterTypeByName)) {
                                throw new RuntimeException("用水类型不存在:" + vo.getUseWaterTypeName());
                            } else {
                                pjMeter.getUserInfo().setUseWaterType(waterTypeByName.getId());
                            }
                        }


                        resulList.add(pjMeter);

                    }

                }
            }


            MessageBean<List> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "工程报装-水表信息导入成功", List.class);
            msg.setData(resulList);
            return msg;
        } catch (Exception e) {
            logger.error("导入失败：", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表导入失败:" + e.getMessage(), null);
        }

    }

    @Override
    public List<HeaderInfoDto> getHeaderInfo(UserInfoBean userInfo) {
        List<HeaderInfoDto> headerInfos = new ArrayList<HeaderInfoDto>();
        headerInfos.add(new HeaderInfoDto("用户编号", true, "userNo"));
        headerInfos.add(new HeaderInfoDto("客户名称", false, "ctmName"));
        headerInfos.add(new HeaderInfoDto("客户证件类型", false, "certTypeName"));
        headerInfos.add(new HeaderInfoDto("客户证件号码", false, "certNo"));
        headerInfos.add(new HeaderInfoDto("客户地址", false, "ctmAddr"));
        headerInfos.add(new HeaderInfoDto("装表地址", false, "setupMeterAddr"));
        headerInfos.add(new HeaderInfoDto("手机号码", false, "mobile"));
        headerInfos.add(new HeaderInfoDto("通知人手机", false, "stopWaterLinkMobile"));
        headerInfos.add(new HeaderInfoDto("用水类型", false, "useWaterTypeName"));
        headerInfos.add(new HeaderInfoDto("开户名称", false, "openAccountName"));
        headerInfos.add(new HeaderInfoDto("开户银行", false, "openAccountBankName"));
        headerInfos.add(new HeaderInfoDto("银行账号", false, "bankAccount"));
        return headerInfos;
    }

    @Override
    public boolean isCheckHeader() {
        return true;
    }
}
